package npu.dce.andcontact1;

import java.io.IOException;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.widget.ImageView; 
import java.io.ByteArrayOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Calendar;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.database.Cursor;
import android.os.Handler;
import android.text.InputFilter;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Toast;

public class Andcontact1 extends Activity {

		private MediaPlayer mMediaPlayer; 

		// UI controls	
		private Button btnSave, btnGroupJoin, btnQuit, btnPhoto, photoButton;
		private EditText editGivenName, editMiddleName, editFamilyName, editPhone, editEmail, 
		         editIM, editStreet, editPOBox, editCity, editState, editZipCode, editCountry, 
		         editSNS, editOrg1, editOrg2, editNotes;
		private RadioButton btnMan, btnWoman;
		private Spinner spinGroupJoin, spinPhone, spinEmail, spinIM, spinPostalAddr, spinSNS, spinOrg1, spinOrg2;
				
		private String strSpinJoin, strVersion, strTypes, strGivenName, strMiddleName, strFamilyName, strMan, strWoman, strSpinPhone, 
			   strPhone, strSpinEmail, strEmail, strSpinIM, strIM, strSpinAddr, strStreet, strPOBox, strCity, strState, strZipCode,
		       strCountry, strSpinSNS, strSNS, strSpinOrg1, strSpinOrg2, strOrg1, strOrg2, strNotes, strTime; 
		
		private static final int SHOW_SUB_NEW_ACTIVITY = 1;
		
		//DB connector
		private ContactDBAdapter mDbHelper;
		private long contact_id, id = 0;	
		
		private String array_groupjoin[], array_phone[], array_email[], array_im[], array_postaladdr[], array_sns[], 
					   array_org1[], array_org2[];
				
		private static final String contactID = "id";
		
		private static final int CAMERA_REQUEST = 1888;  
	    private ImageView imageView; 
	       
		private Handler mHandler = new Handler(); 
		private Context context;
		
		@Override
		protected void onCreate(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onCreate(savedInstanceState);
			setContentView(R.layout.main);
 
			this.mDbHelper = new ContactDBAdapter(this);                  
	        this.imageView = (ImageView)this.findViewById(R.id.imageView1); 
	        photoButton = (Button) this.findViewById(R.id.imagebutton); 
	        
	        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
	        	        
	        //Initialize all the UI controls
	        this.initialize();
	                       
	        Intent intent = getIntent();
	        this.id = intent.getLongExtra(contactID, 0);
	       
	        if(id != 0){
	        	this.getNamePhone(id);
	        	btnSave.setText("Update");	        	
	        }	
	        
	        btnGroupJoin.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) { 
	                    	
	            	try {
	            		
	            		final String CLIENTIP = "10.0.2.2";
	                    final int CLIENTPORT = 500;
	                    
						InetAddress iadd = InetAddress.getByName(CLIENTIP);
						DatagramSocket socket = new DatagramSocket();
						
						JSONObject jsonUpdate = new JSONObject();  

						strSpinJoin = spinGroupJoin.getSelectedItem().toString();
						
						jsonUpdate.put("Join", strSpinJoin); 
									
						// json string representation of person object  
						String stringUpdate = jsonUpdate.toString();  
				
						DatagramPacket packet = new DatagramPacket( stringUpdate.getBytes(), stringUpdate.getBytes().length, iadd, CLIENTPORT);
						socket.send(packet);         			
						  											
					} catch (UnknownHostException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SocketException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}    			    	            	
	            }
	        });
	        
	        photoButton.setOnClickListener(new View.OnClickListener() {         	 
	            @Override 
	            public void onClick(View v) { 
	                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);  
	                startActivityForResult(cameraIntent, CAMERA_REQUEST);  
	            } 
	        }); 

	        btnSave.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View v) { 
	            		            	
	            	strVersion = "1";
	            	strTypes = "update";     
	            		            	            	            	             	            
	            	BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable(); 
	            	Bitmap bitmap = drawable.getBitmap(); 
	            		            	              	
	            	ByteArrayOutputStream out = new ByteArrayOutputStream();
	            	bitmap.compress(CompressFormat.JPEG, 0, out);
	            		            	                        	
	            	int size = bitmap.getRowBytes() * bitmap.getHeight(); 
	            	final byte[] photo = out.toByteArray();                        		
	            	
	            	Context context = getApplicationContext();
	            	int duration = Toast.LENGTH_SHORT;
	            		            	            	
	            	Toast toast1 = Toast.makeText(context, Integer.toString(photo.length), duration);
	            	toast1.show();
	            	            	
	            	if (editGivenName.getText().toString().equals(""))
	            		strGivenName = "null";
	            	else
	            		strGivenName = editGivenName.getText().toString();   
	            		            	
	            	if (editMiddleName.getText().toString().equals(""))
	            		strMiddleName = "M";
	            	else
	            		strMiddleName = editMiddleName.getText().toString();  
	            		             
	            	if (editFamilyName.getText().toString().equals(""))
	            		strFamilyName = "null";
	            	else
	            		strFamilyName = editFamilyName.getText().toString();  
	            		            	            	           
	            	strMan = btnMan.getText().toString(); 
	            	strWoman = btnWoman.getText().toString();                              
	            		                
	            	strSpinPhone = spinPhone.getSelectedItem().toString();
	            		                
	            	if (editPhone.getText().toString().equals(""))
	            		strPhone = "null";
	            	else
	            		strPhone = editPhone.getText().toString();  
	            		                                
	            	strSpinEmail = spinEmail.getSelectedItem().toString();
	            		                
	            	if (editEmail.getText().toString().equals(""))
	            		strEmail = "null";
	            	else
	            		strEmail = editEmail.getText().toString();  
	            		                                
	            	strSpinIM = spinIM.getSelectedItem().toString();
	            		                
	            	if (editIM.getText().toString().equals(""))
	            		strIM = "null";
	            	else
	            		strIM = editIM.getText().toString();  
	            		                                             
	            	strSpinAddr = spinPostalAddr.getSelectedItem().toString();
	            		                
	            	if (editStreet.getText().toString().equals(""))
	            		strStreet = "null";
	            	else
	            		strStreet = editStreet.getText().toString();  
	            		                
	            	if (editPOBox.getText().toString().equals(""))
	            		strPOBox = "null";
	            	else
	            		strPOBox = editPOBox.getText().toString(); 
	            		                
	            	if (editCity.getText().toString().equals(""))
	            		strCity = "null";
	            	else
	            		strCity = editCity.getText().toString(); 
	            		                
	            	if (editState.getText().toString().equals(""))
	            		strState = "null";
	            	else
	            		strState = editState.getText().toString(); 
	            		                
	            	if (editZipCode.getText().toString().equals(""))
	            		strZipCode = "null";
	            	else
	            		strZipCode = editZipCode.getText().toString(); 
	            		                
	            	if (editCountry.getText().toString().equals(""))
	            		strCountry = "null";
	            	else
	            		strCountry = editCountry.getText().toString(); 
	            		                                                
	            	strSpinSNS = spinSNS.getSelectedItem().toString();
	            		                
	            	if (editSNS.getText().toString().equals(""))
	            		strSNS = "null";
	            	else
	            		strSNS = editSNS.getText().toString(); 
	            		                                        
	            	strSpinOrg1 = spinOrg1.getSelectedItem().toString();
	            		                
	            	if (editOrg1.getText().toString().equals(""))
	            		strOrg1 = "null";
	            	else
	            		strOrg1 = editOrg1.getText().toString(); 
	            		                                                
	            	strSpinOrg2 = spinOrg2.getSelectedItem().toString();
	            		                
	            	if (editOrg2.getText().toString().equals(""))
	            		strOrg2 = "null";
	            	else
	            		strOrg2 = editOrg2.getText().toString(); 
	            		                
	            	if (editNotes.getText().toString().equals(""))
	            		strNotes = "null";
	            	else
	            		strNotes = editNotes.getText().toString(); 
	            		                                               
	            	strTime = Long.toString(System.currentTimeMillis());
	            		                             
	            	if(btnMan.isChecked() == true)
	            		strWoman = strMan;
	            		            	
	            	mDbHelper.open();
          		      	            	
	            	builder.setMessage("Are " + strGivenName + " " + strFamilyName +  " phone owner?")
	            	       .setCancelable(false)
	            	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	            	           public void onClick(DialogInterface dialog, int dialog_id) {
	            	        	   
	            	        	   if(id == 0)
	           	            			contact_id = mDbHelper.createContact(strVersion, strTypes, "Y", strGivenName, strMiddleName, strFamilyName, strWoman, strSpinPhone, strPhone, 
	           	            					strSpinEmail, strEmail, strSpinIM, strIM, strSpinAddr, strStreet, strPOBox, strCity, strState, 
	           	            					strZipCode, strCountry, strSpinSNS, strSNS, strSpinOrg1, strOrg1, strSpinOrg2, strOrg2, strNotes, strTime, photo);            	            	
	           	            		else
	           	            			mDbHelper.updateContact(id, strVersion, strTypes, "Y", strGivenName, strMiddleName, strFamilyName, strWoman, strSpinPhone, strPhone, 
	           	            					strSpinEmail, strEmail, strSpinIM, strIM, strSpinAddr, strStreet, strPOBox, strCity, strState, 
	           	            					strZipCode, strCountry, strSpinSNS, strSNS, strSpinOrg1, strOrg1, strSpinOrg2, strOrg2, strNotes, strTime, photo);
	           	           		
	           	            		mDbHelper.close();            	
	           	            		 
	           	            		openDisplayContact_Activity();	
          	            	
	            	           }
	            	       })
	            	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
	            	           public void onClick(DialogInterface dialog, int dialog_id) {
	            	        	   
	            	        	   if(id == 0)
	           	            			contact_id = mDbHelper.createContact(strVersion, strTypes, "N", strGivenName, strMiddleName, strFamilyName, strWoman, strSpinPhone, strPhone, 
	           	            					strSpinEmail, strEmail, strSpinIM, strIM, strSpinAddr, strStreet, strPOBox, strCity, strState, 
	           	            					strZipCode, strCountry, strSpinSNS, strSNS, strSpinOrg1, strOrg1, strSpinOrg2, strOrg2, strNotes, strTime, photo);            	            	
	           	            		else
	           	            			mDbHelper.updateContact(id, strVersion, strTypes, "N", strGivenName, strMiddleName, strFamilyName, strWoman, strSpinPhone, strPhone, 
	           	            					strSpinEmail, strEmail, strSpinIM, strIM, strSpinAddr, strStreet, strPOBox, strCity, strState, 
	           	            					strZipCode, strCountry, strSpinSNS, strSNS, strSpinOrg1, strOrg1, strSpinOrg2, strOrg2, strNotes, strTime, photo);
	           	           		
	           	            		mDbHelper.close();            	
	           	            		openDisplayContact_Activity();	            	
	           	            		
	            	           }
	            	       });
	            	
	            	AlertDialog alert = builder.create();
	            	alert.show();            		    	            		            	
	            }
	        }); 

	        btnQuit.setOnClickListener(new View.OnClickListener() {
	        	
	            public void onClick(View v) {            	
	            	System.exit(0);
	            }
	        });
	        
	        UpdatePacket update = new UpdatePacket();
    
	        Thread t_invite = new Thread(new Server_Invite(context, mHandler, update, mDbHelper));
	        t_invite.start();
	        
		} //onCreate
		
		public boolean onCreateOptionsMenu(Menu menu){
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.menu_displaycontacts, menu);
			return true;
		}

		@Override
		public boolean onOptionsItemSelected(MenuItem item){		
			//Handle Item selected
			switch(item.getItemId()){
			case R.id.menu_displaycontact:
				this.openDisplayContact_Activity();			
				return true;
				
			case R.id.menu_revert:
				this.openDisplayContact_Activity();		
				return true;
			
			case R.id.menu_sync:
				this.openSyncContacts_Activity();		
				return true;
				
			default:
				return (super.onOptionsItemSelected(item));//super class returns false		
			}		
		}
	    	
		public void openDisplayContact_Activity(){
			
			Intent intent = new Intent(Andcontact1.this, UI_DisplayContacts.class);
			startActivity(intent);
			
		}
		
		public void openSyncContacts_Activity(){
						
			Intent myIntent1 = new Intent(getBaseContext(), MyScheduledReceiver_Group.class);
			Intent myIntent2 = new Intent(getBaseContext(), MyScheduledReceiver.class);
						
			PendingIntent pendingIntent1 = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent1, 0);
			PendingIntent pendingIntent2 = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent2, 0);
			
			AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
						
			Calendar calendar1 = Calendar.getInstance();
			Calendar calendar2 = Calendar.getInstance();
			
			// 5 AM  
//		    calendar.set(Calendar.HOUR_OF_DAY, 5); 
//		    calendar.set(Calendar.MINUTE, 0); 
//		    calendar.set(Calendar.SECOND, 0); 
		   		    	
			calendar1.setTimeInMillis(System.currentTimeMillis());
			calendar1.add(Calendar.SECOND, 10);	
			
			calendar2.setTimeInMillis(System.currentTimeMillis());
			calendar2.add(Calendar.SECOND, 20);	
			
			long interval1 = 60 * 1000;	
			long interval2 = 120 * 1000;	
			
//			alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
			
			alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar1.getTimeInMillis(), interval1, pendingIntent1);
			alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(), interval2, pendingIntent2);
			
			finish();
		
		}

	    public void onActivityResult(int requestCode, int resultCode, Intent data) {   
	        
	    	if (requestCode == CAMERA_REQUEST) {   
	            Bitmap photo = (Bitmap) data.getExtras().get("data");  
	            
	            int size = photo.getRowBytes() * photo.getHeight();
	            
	            imageView.setImageBitmap(photo); 
	        }   
	    
	    }
	    
		public void initialize() {
					
			btnSave = (Button) findViewById(R.id.buttonSave);
	        btnQuit = (Button) findViewById(R.id.btnQuit);
	        btnGroupJoin = (Button) findViewById(R.id.btnGroupJoin);
	        btnPhoto = (Button) findViewById(R.id.imagebutton);

	        editGivenName = (EditText) findViewById(R.id.txtGivenName);
	               
	        editGivenName
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                10) });
	        
	        editMiddleName = (EditText) findViewById(R.id.txtMiddleName);
	                
	        editMiddleName
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                5) });
	        
	        editFamilyName = (EditText) findViewById(R.id.txtFamilyName);
	       
	        editFamilyName
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                10) });
	        
	        btnMan = (RadioButton)findViewById(R.id.SexMan); 
	        btnWoman = (RadioButton)findViewById(R.id.SexWoman); 
        
	        editPhone = (EditText) findViewById(R.id.txtPhone);
	        
	        editPhone
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                13) });
	        
	        editEmail = (EditText) findViewById(R.id.txtEmail);
	        
	        editEmail
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                20) });
	        
	        editIM = (EditText) findViewById(R.id.txtIM);
	        
	        editIM
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                20) });
	        
	        editStreet =  (EditText) findViewById(R.id.txtStreet);
	        
	        editStreet
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                10) });
	        
	        editPOBox = (EditText) findViewById(R.id.txtPOBox);
	        
	        editPOBox
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                10) });
	        
	        editCity = (EditText) findViewById(R.id.txtCity);
	        
	        editCity
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                10) });
	        
	        editState = (EditText) findViewById(R.id.txtState);
	        
	        editState
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                10) });
	                
	        editZipCode = (EditText) findViewById(R.id.txtZipCode);
	        
	        editZipCode
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                10) });
	        
	        editCountry = (EditText) findViewById(R.id.txtCountry);
	        
	        editCountry
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                10) });
	        
	        editSNS = (EditText) findViewById(R.id.txtSNS);
	        
	        editSNS
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                20) });
	        
	        editOrg1 = (EditText) findViewById(R.id.txtOrg1);
	        
	        editOrg1
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                10) });
	        
	        editOrg2 = (EditText) findViewById(R.id.txtOrg2);
	        
	        editOrg2
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                10) });
	        
	        editNotes = (EditText) findViewById(R.id.txtNotes);

	        editNotes
	        .setFilters(new InputFilter[]
	        {
	            new InputFilter.LengthFilter(
	                20) });
	        
	        //Spinner Group Join
	        array_groupjoin = new String[2];
	        array_groupjoin[0]="NPU-DCE";
	        array_groupjoin[1]="NPU-DBA"; 
	        spinGroupJoin = (Spinner) findViewById(R.id.spinnerGroupJoin);
	        ArrayAdapter adapter_groupjoin = new ArrayAdapter(this, android.R.layout.simple_spinner_item, array_groupjoin);
	        spinGroupJoin.setAdapter(adapter_groupjoin);
	        
	        //Spinner Phone
	        array_phone = new String[5];
	        array_phone[0]="Home";
	        array_phone[1]="Home Fax";
	        array_phone[2]="Mobile";
	        array_phone[3]="Work";
	        array_phone[4]="Work Fax";
	        spinPhone = (Spinner) findViewById(R.id.spinnerPhone);
	        ArrayAdapter<String> adapter_phone = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array_phone);
	        spinPhone.setAdapter(adapter_phone);

	        //Spinner Email
	        array_email = new String[4];
	        array_email[0]="Home";
	        array_email[1]="Work";
	        array_email[2]="Mobile";
	        array_email[3]="Other";
	        spinEmail = (Spinner) findViewById(R.id.spinnerEmail);
	        ArrayAdapter<String> adapter_email = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array_email);
	        spinEmail.setAdapter(adapter_email);
	        
	        //Spinner IM
	        array_im = new String[4];
	        array_im[0]="Yahoo";
	        array_im[1]="Skype";
	        array_im[2]="GoogleTalk";
	        array_im[3]="Windows Live";
	        spinIM = (Spinner) findViewById(R.id.spinnerIM);
	        ArrayAdapter<String> adapter_im = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array_im);
	        spinIM.setAdapter(adapter_im); 
	        
	        //Spinner  Postal Address
	        array_postaladdr = new String[2];
	        array_postaladdr[0]="Home";
	        array_postaladdr[1]="Work";
	        spinPostalAddr = (Spinner) findViewById(R.id.spinnerPostalAddress);
	        ArrayAdapter<String> adapter_addr = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array_postaladdr);
	        spinPostalAddr.setAdapter(adapter_addr);
	        
	        //Spinner SNS
	        array_sns = new String[6];
	        array_sns[0]="Facebook";
	        array_sns[1]="Twitter";
	        array_sns[2]="Buzz";
	        array_sns[3]="Orkut";
	        array_sns[4]="Cyworld";
	        array_sns[5]="MySpace";
	        spinSNS = (Spinner) findViewById(R.id.spinnerSNS);
	        ArrayAdapter<String> adapter_sns = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array_sns);
	        spinSNS.setAdapter(adapter_sns);
	        
	        //Spinner Organization1
	        array_org1 = new String[6];
	        array_org1[0]="R&D";
	        array_org1[1]="Marketing";
	        array_org1[2]="Sales";
	        array_org1[3]="Operation";
	        array_org1[4]="HR";
	        array_org1[5]="QA";
	        spinOrg1 = (Spinner) findViewById(R.id.spinnerOrg1);
	        ArrayAdapter adapter_org1 = new ArrayAdapter(this, android.R.layout.simple_spinner_item, array_org1);
	        spinOrg1.setAdapter(adapter_org1); 
	        
	        //Spinner Organization2
	        array_org2 = new String[10];
	        array_org2[0]="BBAIS";
	        array_org2[1]="BSCS";
	        array_org2[2]="BSCSE";
	        array_org2[3]="BSEE";
	        array_org2[4]="MBA";
	        array_org2[5]="MSEE";
	        array_org2[6]="MSCSE";
	        array_org2[7]="MSCS";
	        array_org2[8]="DBA";
	        array_org2[9]="DCE";        
	        spinOrg2 = (Spinner) findViewById(R.id.spinnerOrg2);
	        ArrayAdapter adapter_org2 = new ArrayAdapter(this, android.R.layout.simple_spinner_item, array_org2);
	        spinOrg2.setAdapter(adapter_org2);
	        
		}
	    
	    public void getNamePhone(long id) {
	        this.mDbHelper.open(); 
	        
	        Cursor cursor = this.mDbHelper.fetchContact(id);
	        
			if(cursor != null)
				cursor.moveToFirst();
	
			byte[] blob = cursor.getBlob(cursor.getColumnIndex(this.mDbHelper.KEY_PHOTO));
			imageView = (ImageView)findViewById(R.id.imageView1);
			imageView.setImageBitmap(BitmapFactory.decodeByteArray(blob, 0, blob.length)); 

			editGivenName.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_GIVENNAME)));
			editMiddleName.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_MIDDLENAME)));
			editFamilyName.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_FAMILYNAME)));

			String gender = cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_GENDER));
			if(gender.equals(btnMan.getText().toString()))			
				btnMan.setChecked(true);
			else
				btnWoman.setChecked(true);

			this.setSpinnerItem(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SPINPHONE)), spinPhone);
			editPhone.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_PHONE)));
			
			this.setSpinnerItem(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SPINEMAIL)), spinEmail);
			editEmail.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_EMAIL)));
			
			this.setSpinnerItem(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SPINIM)), spinIM);
			editIM.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_IM)));		       

			this.setSpinnerItem(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SPINADDR)), spinPostalAddr);
			editStreet.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_STREET)));
			editPOBox.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_POBOX)));
			editCity.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_CITY)));
			editState.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_STATE)));
			editZipCode.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_ZIPCODE)));
			editCountry.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_COUNTRY)));
							
			this.setSpinnerItem(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SPINSNS)), spinSNS);
			editSNS.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SNS)));
			
			this.setSpinnerItem(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SPINORG1)), spinOrg1);
			editOrg1.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_ORG1)));
			
			this.setSpinnerItem(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_SPINORG2)), spinOrg2);
			editOrg2.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_ORG2)));
			
			editNotes.setText(cursor.getString(cursor.getColumnIndex(this.mDbHelper.KEY_NOTES)));

			cursor.close();

	        this.mDbHelper.close();	
	    }
	    
	    public void setSpinnerItem(String text, Spinner spinner) {
	    	ArrayAdapter adapter = (ArrayAdapter)spinner.getAdapter();
	    	int pos = adapter.getPosition(text);
	    	spinner.setSelection(pos);
	    }
	    
	    public void hideNewContactScr(long id)
	    {
	    	Uri data = Uri.parse(Long.toString(id));
	    	Intent result = new Intent(null,data);
	    	setResult(RESULT_OK, result);
	    	finish();
	    }    
	
		public void playSound(Context context, Uri alert) {
			mMediaPlayer = new MediaPlayer();
		
			try {
				mMediaPlayer.setDataSource(context, alert);
				final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		
				if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
					mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
					mMediaPlayer.prepare();
					mMediaPlayer.start();
				}
				
			} catch (IOException e) {
				System.out.println("OOPS");
			}
		}
		//Get an alarm sound. Try for an alarm. If none set, try notification, 
		//Otherwise, ringtone.
		public Uri getAlarmUri() {
		
			Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
		
			if (alert == null) {
				
				alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
				
				if (alert == null) {
					alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
				}
			}
			return alert;
		}	
		
}